package com.duofan.gmall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.duofan.gmall.common.constant.ProductConstant;
import com.duofan.gmall.common.to.SkuHasStockTo;
import com.duofan.gmall.common.to.SkuReductionTo;
import com.duofan.gmall.common.to.SpuBoundsTo;
import com.duofan.gmall.common.to.es.SkuEsModel;
import com.duofan.gmall.common.utils.R;
import com.duofan.gmall.product.entity.*;
import com.duofan.gmall.product.feign.CouponFeignService;
import com.duofan.gmall.product.feign.SearchFeignService;
import com.duofan.gmall.product.feign.WareFeignService;
import com.duofan.gmall.product.service.*;
import com.duofan.gmall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duofan.gmall.common.utils.PageUtils;
import com.duofan.gmall.common.utils.Query;

import com.duofan.gmall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    AttrService attrService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    BrandService brandService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveSpuInfo(SpuSaveVo vo) {
        // 1 保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.baseMapper.insert(spuInfoEntity);

        Long spuId = spuInfoEntity.getId();

        // 2 保存spu描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        if(!CollectionUtils.isEmpty(decript)) {
            SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
            spuInfoDescEntity.setSpuId(spuId);
            spuInfoDescEntity.setDecript(String.join(",", decript));
            spuInfoDescService.save(spuInfoDescEntity);
        }

        // 3 保存spu图片集 pms_spu_images
        List<String> imgs = vo.getImages();
        if(!CollectionUtils.isEmpty(imgs)) {
            List<SpuImagesEntity> spuImagesEntities = imgs.stream().map(e -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuId);
                spuImagesEntity.setImgUrl(e);
                return spuImagesEntity;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(spuImagesEntities);
        }


        // 4 保存spu规格参数
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        if(!CollectionUtils.isEmpty(baseAttrs)) {
            List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(e -> {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setAttrId(e.getAttrId());
                AttrEntity attrEntity = attrService.getById(e.getAttrId());
                productAttrValueEntity.setAttrName(attrEntity.getAttrName());
                productAttrValueEntity.setAttrValue(e.getAttrValues());
                productAttrValueEntity.setQuickShow(e.getShowDesc());
                productAttrValueEntity.setSpuId(spuId);
                return productAttrValueEntity;
            }).collect(Collectors.toList());
            productAttrValueService.saveBatch(productAttrValueEntities);
        }

        // 5 保存spu积分信息
        Bounds bounds = vo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuId);
        R r = couponFeignService.saveSpuBounds(spuBoundsTo);
        if(r.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }

        // 6 保存spu对应的sku信息 pms_product_attr_value
        List<Skus> skus = vo.getSkus();

        // 6.1 sku基本信息 pms_sku_info
        if(!CollectionUtils.isEmpty(skus)) {
            skus.forEach(sku -> {
                String defaultImg = null;
                for(Images img : sku.getImages()) {
                    if(img.getDefaultImg() == 1) {
                        defaultImg = img.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuId);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.save(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                // 6.2 sku图片信息 pms_sku_images
                List<Images> images = sku.getImages();
                if(!CollectionUtils.isEmpty(images)) {
                    List<SkuImagesEntity> imagesEntities = images.stream().map(img -> {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        skuImagesEntity.setSkuId(skuId);
                        skuImagesEntity.setImgUrl(img.getImgUrl());
                        skuImagesEntity.setDefaultImg(img.getDefaultImg());
                        return skuImagesEntity;
                    // 没有图片路径的无需保存
                    }).filter(e -> StringUtils.isEmpty(e.getImgUrl() != null))
                    .collect(Collectors.toList());
                    skuImagesService.saveBatch(imagesEntities);
                }

                // 6.3 sku销售属性信息 pms_sku_sale_attr_value
                List<Attr> attrs = sku.getAttr();
                if(CollectionUtils.isEmpty(attrs)) {
                    List<SkuSaleAttrValueEntity> valueEntities = attrs.stream().map(attr -> {
                        SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                        skuSaleAttrValueEntity.setSkuId(skuId);
                        return skuSaleAttrValueEntity;
                    }).collect(Collectors.toList());
                    skuSaleAttrValueService.saveBatch(valueEntities);
                }

                // 6.4 sku优惠和满减信息
                // gmall-> sms_sku_ladder \ sms_sku_full_reduction \ sms_member_price
                if(sku.getFullCount() > 0 || sku.getFullPrice().compareTo(new BigDecimal(0)) == 1) {
                    SkuReductionTo skuReductionTo = new SkuReductionTo();
                    BeanUtils.copyProperties(sku, skuReductionTo);
                    skuReductionTo.setSkuId(skuId);
                    R r2 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if(r2.getCode() != 0) {
                        log.error("远程保存满减和优惠信息失败");
                    }
                }
            });
        }
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String)params.get("key");
        if(!StringUtils.isEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        String status = (String)params.get("status");
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }
        String brandId = (String)params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String catelogId = (String)params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        // 查当前spuId对应的sku
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);
        List<Long> skuIds = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        // 查询当前sku所有可以检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseArrtListForSpu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        // 查询可以检索的属性Id
        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
        Set<Long> idSet = new HashSet<>(searchAttrIds);

        // 过滤出可以检索的属性
        List<SkuEsModel.Attr> attrs = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attr attr = new SkuEsModel.Attr();
            BeanUtils.copyProperties(item, attr);
            return attr;
        }).collect(Collectors.toList());

        // 远程查询是否有库存
        Map<Long, Boolean> hasStockMap = null;
        try {
            R r = wareFeignService.getSkusHasStock(skuIds);
            hasStockMap = r.getData(new TypeReference<List<SkuHasStockTo>>(){}).stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId,
                    SkuHasStockTo::getHasStock));
        } catch (Exception e) {
            log.error("库存服务查询异常: {}", e);
        }


        final Map<Long, Boolean> hasStockMapFinal = hasStockMap;
        // 封装每个sku的信息
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, esModel);
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());
            // 网络波动,默认设置有库存
            if(hasStockMapFinal == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(hasStockMapFinal.get(sku.getSkuId()));
            }
            // TODO 热度评分
            esModel.setHotScore(0L);
            //询品牌和分类的名字
            BrandEntity brandEntity = brandService.getById(esModel.getBrandId());
            esModel.setBrandName(brandEntity.getName());
            esModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(esModel.getCatalogId());
            esModel.setCatalogName(categoryEntity.getName());
            esModel.setAttrs(attrs);
            return esModel;
        }).collect(Collectors.toList());

        // 数据发送给ES保存
        R r = searchFeignService.productStatusUp(upProducts);
        if(r.getCode() == 0) {
            // 远程调用成功,修改Spu状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
            log.info("商品上架完成");
        } else {
            // 远程调用失败
            // TODO 重复调用问题,接口幂等
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        Long spuId = skuInfoEntity.getSpuId();
        return this.getById(spuId);
    }
}